package com.cssnj.portal.web.filter;

import com.cssnj.portal.service.user.PermissionService;
import io.predictech.framework.domain.constants.SysConstants;
import io.predictech.framework.utility.SpringContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class URLPathMatchingFilter extends PathMatchingFilter {

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        String requestURI = getPathWithinApplication(request);
        Subject subject = SecurityUtils.getSubject();
        // 如果没有登录，就跳转到登录页面
        if (!subject.isAuthenticated()) {
            WebUtils.issueRedirect(request, response, SpringContextUtil.getApplicationContext().getEnvironment().getProperty(SysConstants.WEB_LOGIN_URL));
            return false;
        } else {
            if (subject.hasRole(SysConstants.SYS_USER_ADMIN)) {
                return true;
            } else {
                PermissionService permissionService = (PermissionService) SpringContextUtil.getApplicationContext().getBean("permissionService");
                if (permissionService.isAdminUrl(requestURI)) {
                    return false;
                }
                boolean needInterceptor = permissionService.needInterceptor(requestURI);
                if (!needInterceptor) {
                    return true;
                } else {
                    try {
                        subject.checkPermission(requestURI);
                        return true;
                    } catch (AuthorizationException e) {
                        return false;
                    }
                }
            }
        }


    }
}
